<template>
    <div class="loginBox">
        <div class="loginWrap">
            <h3>登录</h3>
            <el-form label-width="100px" class="demo-ruleForm" :model="user" :rules="rules" ref="loginForm">
                <el-form-item label="账号" prop="username">
                    <el-input v-model="user.username"></el-input>
                </el-form-item>
                <el-form-item label="密码" prop="password">
                    <el-input v-model="user.password"></el-input>
                </el-form-item>
                <el-form-item>
                    <el-button type="primary" @click="login">登录</el-button>
                </el-form-item>
            </el-form>
        </div>

    </div>
</template>
<script>
import { userLogin } from '../request/api';
export default {
    data() {
        return {
            user: {
                username: '',
                password: ''
            },
            rules: {
                username: [
                    { required: true, message: '请输入账号', trigger: 'blur' },
                    { min: 2, max: 8, message: '长度在 2 到 8 个字符', trigger: 'blur' }
                ],
                password: [
                    { required: true, message: '请输入密码', trigger: 'blur' },
                    { min: 6, max: 12, message: '长度在 6 到 12 个字符', trigger: 'blur' }
                ],
            }
        }
    },
    methods: {
        // 点击回车  实现登陆
        keyDown(e) {
            if (e.keyCode == 13) {
                // console.log('回车');
                this.login();

            }
        },

        // 登录
        login() {
            // 获取元素使用validate方法 检验表单每一项 是否符合规则
            this.$refs.loginForm.validate(value => {
                if (value) {
                    userLogin(this.user).then(res => {
                        if (res.code == 200) {
                            // console.log(res);
                            // 登录成功
                            this.$message.success(res.msg);
                            // 将登录信息存储到仓库中  先存储后跳转
                            this.$store.commit('CHANGE_USERINFO', res.list)
                            // sessionStorage.setItem('userInfo',JSON.stringify(res.list))
                            // 跳转首页
                            this.$router.push('/menu');
                        } else {
                            // 登录失败
                            this.$message.error(res.msg);
                        }
                    })
                }
            })
        }
    },
    mounted() {
        window.addEventListener('keydown', this.keyDown)
    },
    watch: {

    },
    computed: {},
    filters: {},
    components: {},
}
</script>
<style lang="less" scoped>
.loginBox {
    width: 100vw;
    height: 100vh;
    background-color: #ccc;
    display: flex;
    justify-content: center;
    align-items: center;

    h3 {
        padding-left: 100px;
    }
}

.loginWrap {
    width: 400px;
    height: 300px;
    text-align: center;
}
</style>